package com.softa.service.business.impl;

import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageInfo;
import com.softa.annotation.ServiceLog;
import com.softa.dao.dto.ProductDTO;
import com.softa.dao.dto.SysUserDTO;
import com.softa.dao.mapper.base.ProductMapper;
import com.softa.dao.mapper.base.ProductTypeMapper;
import com.softa.dao.mapper.base.SysFileMapper;
import com.softa.dao.mapper.relation.business.ProductRelationMapper;
import com.softa.dao.model.Product;
import com.softa.dao.model.ProductType;
import com.softa.dao.model.SysFile;
import com.softa.enummodel.FileTypeEnum;
import com.softa.service.business.ProductService;
import com.softa.service.system.SysFileService;
import com.softa.vo.DataGridRequest;
import com.softa.vo.QueryRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.PictureData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by yangl on 2017/8/8.
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductRelationMapper productRelationMapper;

    @Autowired
    private SysFileMapper sysFileMapper;

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private ProductTypeMapper productTypeMapper;

    @Override
    public PageInfo<ProductDTO> queryProductByParam(DataGridRequest request, final QueryRequest queryRequest) {
        PageInfo<ProductDTO> page = request.startPagePlugin().doSelectPageInfo(new ISelect() {
            @Override
            public void doSelect() {
                productRelationMapper.selectByCondition(queryRequest);
            }
        });
        return  page;
    }

    @Override
    public PageInfo<ProductDTO> queryProductPicByParam(DataGridRequest request, final QueryRequest queryRequest) {
        PageInfo<ProductDTO> page = request.startPagePlugin().doSelectPageInfo(new ISelect() {
            @Override
            public void doSelect() {
                productRelationMapper.selectByCondition(queryRequest);
            }
        });
        List<ProductDTO> list = page.getList();
        for(ProductDTO pro : list){
            pro.setPicFirstId(getFirstPicId(pro.getId()));
        }
        return  page;
    }

    public Long getFirstPicId(Long id){
      return sysFileService.getFirstPicId(id);
    }

    @Override
    public ProductDTO getProductDTOById(Long id){
        Product product = productMapper.selectByPrimaryKey(id);
        ProductDTO productDTO = new ProductDTO();
        BeanUtils.copyProperties(product, productDTO);
        //查询附件
        QueryRequest queryRequest = new QueryRequest();
        queryRequest.getParams().put("pkeyId", id.toString());
        queryRequest.getParams().put("tableName", Product.class.getSimpleName());
        List<SysFile> sysFiles = sysFileService.selectByCondition(queryRequest);
        Long videoId = null;
        List<Long> picIds = new ArrayList<>();
        for(SysFile sysFile : sysFiles){
            if(FileTypeEnum.IMAGE.toString().equals(sysFile.getFileType())){
                picIds.add(sysFile.getId());
            }else{
                videoId = sysFile.getId();
            }
        }

        productDTO.setVideoId(videoId);
        productDTO.setPics(picIds);
        if(CollectionUtils.isNotEmpty(picIds)){
            productDTO.setPicFirstId(picIds.get(0));
        }
        //类型名称
        if(null != product.getTypeId()){
            ProductType productType = productTypeMapper.selectByPrimaryKey(product.getTypeId());
            if(null != productType){
                productDTO.setTypeName(productType.getName());
            }
        }
        return productDTO;
    }

    @Override
    @ServiceLog("添加产品")
    public String createProduct(ProductDTO productDTO) {
        QueryRequest queryRequest = new QueryRequest();
        queryRequest.getParams().put("no", productDTO.getNo());
        boolean isexists = isExists(queryRequest);
        if(isexists){
            return "1";
        }else{
            queryRequest.getParams().put("no", null);
            queryRequest.getParams().put("name", productDTO.getName());
            isexists = isExists(queryRequest);
            if(isexists){
                return "2";
            }else{
                Product product = new Product();
                BeanUtils.copyProperties(productDTO, product);
                product.setCreateTime(new Date());
                product.setUpdateTime(new Date());
                product.setDeleted(false);
                //默认下架
                product.setStatus(0);
                product.setVersion((productDTO.getVersion() == null?0:productDTO.getVersion())+1);
                productRelationMapper.insertSelective(product);
                Long id = product.getId();
                buildFile(productDTO, id);
                return "录入成功";
            }
        }
    }

    @Override
    @ServiceLog("修改产品")
    public String updateProduct(ProductDTO productDTO) {
        Long id = productDTO.getId();
        QueryRequest queryRequest2 = new QueryRequest();
        queryRequest2.getParams().put("no", productDTO.getNo());
        queryRequest2.getParams().put("id", id);
        boolean isexists = isExists(queryRequest2);
        if(isexists){
            return "1";
        }else{
            queryRequest2.getParams().put("no", null);
            queryRequest2.getParams().put("name", productDTO.getName());
            isexists = isExists(queryRequest2);
            if(isexists){
                return "2";
            }else{
                Product product = new Product();
                BeanUtils.copyProperties(productDTO, product);
                product.setUpdateTime(new Date());
                productRelationMapper.updateByPrimaryKeySelective(product);
                //删除以前存在的
                QueryRequest queryRequest = new QueryRequest();
                queryRequest.getParams().put("pkeyId", id.toString());
                queryRequest.getParams().put("tableName", Product.class.getSimpleName());
                List<Long> pics = productDTO.getPics();
                List<Long> list = new ArrayList<>();
                for(Long pid : pics){
                    if(null != pid){
                        list.add(pid);
                    }
                }
                if(null != productDTO.getVideoId()){
                    list.add(productDTO.getVideoId());
                }
                queryRequest.getParams().put("ids", list);
                sysFileService.deleteByPkeyIdAndTableName(queryRequest);
                buildFile(productDTO, id);
                return "修改成功";
            }
        }
    }

    @Override
    @ServiceLog("删除产品")
    public String deleteProduct(Product product) {
        product.setUpdateTime(new Date());
        product.setDeleted(true);
        Long id = product.getId();
        productMapper.updateByPrimaryKeySelective(product);
        //删除以前存在的
        QueryRequest queryRequest = new QueryRequest();
        queryRequest.getParams().put("pkeyId", id.toString());
        queryRequest.getParams().put("tableName", Product.class.getSimpleName());
        sysFileService.deleteByPkeyIdAndTableName(queryRequest);
        return "提交成功";
    }

    @Override
    @ServiceLog("改变产品状态")
    public String changeStatus(Product product) {
        product.setUpdateTime(new Date());
        productMapper.updateByPrimaryKeySelective(product);
        return "提交成功";
    }


    /**
     * 保存产品附件
     * @param productDTO
     * @param id 产品id
     */
    public void buildFile(ProductDTO productDTO, Long id){
        //更新video
        if(null != productDTO.getVideoId()){
            saveSysFile(productDTO.getVideoId(), id);
        }
        //更新图片
        List<Long> pics = productDTO.getPics();
        if(CollectionUtils.isNotEmpty(pics)){
            for(Long picid : pics){
                saveSysFile(picid, id);
            }
        }
    }

    public void saveSysFile(Long fileId, Long productId){
        SysFile sysFile = new SysFile();
        sysFile.setId(fileId);
        sysFile.setPkeyId(productId.toString());
        sysFile.setTableName(Product.class.getSimpleName());
        sysFileMapper.updateByPrimaryKeySelective(sysFile);
    }

    public boolean  isExists(QueryRequest queryRequest){
        Long count = productRelationMapper.selectCountByCondition(queryRequest);
        if(count > 0 ){
            return true;
        }else{
            return false;
        }
    }

}
